#!/usr/bin/env python3
"""
简单心跳上报示例
这是一个最简化的示例，展示如何快速使用心跳接口
"""

import requests
import json
import time
from motor.resources.endpoint import EndpointStatus


def simple_heartbeat_example():
    """简单心跳发送示例"""
    
    # 控制器地址
    controller_url = "http://localhost:57675/controller/heartbeat"
    
    # 心跳数据
    heartbeat_data = {
        "job_name": "simple_job",
        "ins_id": 1,
        "ip": "127.0.0.1",
        "status": {
            0: EndpointStatus.NORMAL.value,
            1: EndpointStatus.NORMAL.value,
            # 2: EndpointStatus.NORMAL.value
        }
    }
    
    try:
        print("发送心跳消息...")
        print(f"数据: {json.dumps(heartbeat_data, indent=2, ensure_ascii=False)}")
        
        # 发送请求
        response = requests.post(controller_url, json=heartbeat_data, timeout=10)
        
        # 检查响应
        if response.status_code == 200:
            result = response.json()
            print(f"心跳发送成功! 响应: {json.dumps(result, indent=2, ensure_ascii=False)}")
        else:
            print(f"心跳发送失败! 状态码: {response.status_code}")
            print(f"错误信息: {response.text}")
            
    except requests.exceptions.ConnectionError:
        print("连接失败! 请确保控制器服务正在运行")
    except requests.exceptions.Timeout:
        print("心跳请求超时!")
    except Exception as e:
        print(f"发生错误: {e}")


def continuous_heartbeat_example():
    """持续心跳发送示例"""
    
    controller_url = "http://localhost:57675/controller/heartbeat"
    
    # 模拟不同的endpoint状态
    endpoint_statuses = [
        {0: EndpointStatus.NORMAL.value, 1: EndpointStatus.NORMAL.value, 2: EndpointStatus.NORMAL.value},
        {0: EndpointStatus.ABNORMAL.value, 1: EndpointStatus.NORMAL.value, 2: EndpointStatus.NORMAL.value},
        {0: EndpointStatus.NORMAL.value, 1: EndpointStatus.PAUSED.value, 2: EndpointStatus.NORMAL.value},
        {0: EndpointStatus.NORMAL.value, 1: EndpointStatus.NORMAL.value, 2: EndpointStatus.ABNORMAL.value},
        {0: EndpointStatus.NORMAL.value, 1: EndpointStatus.NORMAL.value, 2: EndpointStatus.NORMAL.value},
    ]
    
    try:
        print("开始持续发送心跳消息...")
        
        for i, status in enumerate(endpoint_statuses):
            heartbeat_data = {
                "job_name": "continuous_job",
                "ins_id": 1,
                "ip": "127.0.0.1",
                "status": status
            }
            
            print(f"\n第 {i+1} 次心跳:")
            print(f"数据: {json.dumps(heartbeat_data, indent=2, ensure_ascii=False)}")
            
            response = requests.post(controller_url, json=heartbeat_data, timeout=10)
            
            if response.status_code == 200:
                result = response.json()
                print(f"心跳发送成功! 响应: {json.dumps(result, indent=2, ensure_ascii=False)}")
            else:
                print(f"心跳发送失败! 状态码: {response.status_code}")
                print(f"错误信息: {response.text}")
            
            # 等待2秒再发送下一次心跳
            if i < len(endpoint_statuses) - 1:
                print("等待2秒...")
                time.sleep(2)
                
    except KeyboardInterrupt:
        print("\n收到中断信号，停止发送心跳")
    except Exception as e:
        print(f"发生错误: {e}")


def multi_endpoint_heartbeat_example():
    """多endpoint心跳示例"""
    
    controller_url = "http://localhost:57675/controller/heartbeat"
    
    # 模拟多个endpoint的不同状态
    heartbeat_data = {
        "job_name": "multi_endpoint_job",
        "ins_id": 1,
        "ip": "127.0.0.1",
        "status": {
            0: EndpointStatus.NORMAL.value,      # endpoint 0 正常
            1: EndpointStatus.ABNORMAL.value,    # endpoint 1 异常
            2: EndpointStatus.PAUSED.value,      # endpoint 2 暂停
            3: EndpointStatus.WAIT2START.value,  # endpoint 3 等待启动
            4: EndpointStatus.NORMAL.value       # endpoint 4 正常
        }
    }
    
    try:
        print("发送多endpoint心跳消息...")
        print(f"数据: {json.dumps(heartbeat_data, indent=2, ensure_ascii=False)}")
        
        response = requests.post(controller_url, json=heartbeat_data, timeout=10)
        
        if response.status_code == 200:
            result = response.json()
            print(f"心跳发送成功! 响应: {json.dumps(result, indent=2, ensure_ascii=False)}")
        else:
            print(f"心跳发送失败! 状态码: {response.status_code}")
            print(f"错误信息: {response.text}")
            
    except Exception as e:
        print(f"发生错误: {e}")


if __name__ == "__main__":
    print("简单心跳上报示例")
    print("请选择运行模式:")
    print("1. 单次心跳发送")
    print("2. 持续心跳发送")
    print("3. 多endpoint心跳发送")
    
    try:
        choice = input("请输入选择 (1-3): ").strip()
        
        if choice == "1":
            simple_heartbeat_example()
        elif choice == "2":
            continuous_heartbeat_example()
        elif choice == "3":
            multi_endpoint_heartbeat_example()
        else:
            print("无效选择，运行单次心跳示例")
            simple_heartbeat_example()
            
    except KeyboardInterrupt:
        print("\n程序被中断")
    except Exception as e:
        print(f"程序发生错误: {e}")
